package com.ling.pl.security.decision;

import com.ling.pl.security.model.DefaultUser;
import com.ling.pl.security.utils.ConfigAttribute;

import java.util.Collection;
import java.util.List;

/**
 * @author bo.wang
 */
public class ComponentAccessDecisionManager {
    public static final String BEAN_ID = "ling2.componentAccessDecisionManager";
    private List<AccessDecisionVoter<Object>> decisionVoters;

    public ComponentAccessDecisionManager(List<AccessDecisionVoter<Object>> decisionVoters) {
        this.decisionVoters = decisionVoters;
    }

    public boolean decide(DefaultUser authentication, Collection<ConfigAttribute> configAttributes) {
        if (authentication.isAdministrator()) return true;

        int result = 10;
        for (AccessDecisionVoter<Object> voter : decisionVoters) {
            result = voter.vote(authentication, null, configAttributes);
            if (result == AccessDecisionVoter.ACCESS_ABSTAIN) {
                continue;
            }
            if (result == AccessDecisionVoter.ACCESS_DENIED) {
                return false;
            }
            if (result == AccessDecisionVoter.ACCESS_GRANTED) {
                break;
            }
        }
        if (result == AccessDecisionVoter.ACCESS_ABSTAIN && configAttributes.size() > 0) {
            return false;
        } else {
            return true;
        }
    }
}
